﻿using System;
using System.IO;
using Microsoft.Win32;

namespace UIControls
{
    class ExternalToolLocations
    {
        /// <summary>
        /// return the location of the console version of ghostscript.
        /// </summary>
        /// <returns></returns>
        public static string LocationGS
        {
            get { CacheGS(); return _gs; }
            set { _gs = value; }
        }

        /// <summary>
        /// Find the ghost script location.
        /// </summary>
        private static void CacheGS()
        {
            if (_gs != null)
            {
                return;
            }

            using (RegistryKey k = Registry.LocalMachine.OpenSubKey("SOFTWARE\\GPL Ghostscript"))
            {
                if (k == null)
                {
                    ///
                    /// Last ditch effort to find things if the registry doesn't show us where it is... this is really fishing in the dark...
                    /// 

                    DirectoryInfo info = new DirectoryInfo(System.Environment.ExpandEnvironmentVariables(@"%SystemDrive%\Program Files\gs"));
                    if (info.Exists)
                    {
                        foreach (DirectoryInfo subdir in info.GetDirectories())
                        {
                            FileInfo gs = new FileInfo(subdir.FullName + @"\bin\gswin32c.exe");
                            if (gs.Exists)
                            {
                                _gs = gs.FullName;
                                return;
                            }
                        }
                    }

                    ///
                    /// No luck!
                    /// 

                    throw new ArgumentException("Could not find ghost script registry key!");
                }
                foreach (var key in k.GetSubKeyNames())
                {
                    using (RegistryKey gsloc = k.OpenSubKey(key))
                    {
                        if (gsloc != null)
                        {
                            _gs = (string)gsloc.GetValue("GS_DLL");
                            if (_gs != null)
                            {
                                _gs = _gs.Substring(0, _gs.LastIndexOf("\\") + 1) + "gswin32c.exe";
                                return;
                            }
                        }
                    }
                }
            }

        }

        /// <summary>
        /// Hold onto the internal location of ghost script's executable.
        /// </summary>
        private static string _gs = null;
    }
}
